import { Component, OnInit } from '@angular/core';
import { NavController, Platform } from '@ionic/angular';
import { HttpService } from 'src/app/service/http.service';
import { UrlService } from 'src/app/service/url.service';
import { ConfigService } from 'src/app/service/config.service';
import { ToolService } from 'src/app/service/tool.service';
import { PopwinService } from 'src/app/service/popwin.service';
import { Clipboard } from '@ionic-native/clipboard/ngx';
import { SocialSharing } from '@ionic-native/social-sharing/ngx';
import { PhotoLibrary } from '@ionic-native/photo-library/ngx';
import { FileTransfer, FileUploadOptions, FileTransferObject } from '@ionic-native/file-transfer/ngx';
import { File } from '@ionic-native/file/ngx';

@Component({
  selector: 'app-recommendapp',
  templateUrl: './recommendapp.page.html',
  styleUrls: ['./recommendapp.page.scss'],
})
export class RecommendappPage implements OnInit {
 public recommend={"img":"","shareUrl":"","url":"","downloadUrl":""}
  constructor(private navCtrl:NavController,private http:HttpService,private popWin:PopwinService,private platform:Platform,private clipboard:Clipboard,private plt:Platform,private socialSharing: SocialSharing,private photoLibrary: PhotoLibrary,
    private transfer:FileTransfer,private file:File) {}

  ngOnInit() {
    this.recommendData();
  }
  backClick() {
    this.navCtrl.navigateBack("tabs/my");
  }

  recommendDataBark(){
    let that = this;
    this.http.get(UrlService.USER_RECOMMENDAPP, {"callback": "JSONP_CALLBACK"}).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let res=ToolService.aesDecodeToJson(temp);
        if(!ToolService.isEmpty(res)){
          that.recommend=res[0];
          console.log(res[0]);
        }
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  recommendData() {
    let that = this;
    let obj = "{\"type\":\"" + "recommend" + "\",\"agent\":\"0\"}";
    this.http.get(UrlService.OTHER_CONFIG, { "callback": "JSONP_CALLBACK" , "data": ToolService.aesEncode(obj)}).subscribe(res => {
      let data = res.json();
      ToolService.setEncrypt(data.encrypt);
      if (data.code == ConfigService.SUCCESS_CODE) {
        let temp = data.data;
        let res = ToolService.aesDecodeToJson(temp);
        that.recommend={"img":ToolService.isEmpty(res.images.mobile)?"":res.images.mobile,"shareUrl":ToolService.isEmpty(res.mobile.cfg_val)?"":res.mobile.cfg_val,"url":ToolService.isEmpty(res.web.cfg_val)?"":res.web.cfg_val,"downloadUrl":ToolService.isEmpty(res.mobile.cfg_val)?"":res.mobile.cfg_val}
        // if(that.plt.is("mobileweb") || that.plt.is("mobile")){
        //     that.recommend={"img":res.images.web,"shareUrl":res.web.cfg_val,"url":res.web.cfg_val,"downloadUrl":res.web.cfg_val}
        // }else if(that.plt.is("android")){
        //   that.recommend={"img":res.android.web,"shareUrl":res.android.cfg_val,"url":res.web.cfg_val,"downloadUrl":res.android.cfg_val}
        // }else if(that.plt.is("ios")){
        //   that.recommend={"img":res.ios.web,"shareUrl":res.ios.cfg_val,"url":res.web.cfg_val,"downloadUrl":res.ios.cfg_val}
        // }
        console.log(res);
      } else if (data.code == ConfigService.FAIL_CODE) {
        that.popWin.toast(data.message);
      } else if (data.code == ConfigService.LOGIN_CODE) {
        that.navCtrl.navigateForward("/login");
      }
    }, error => {
      console.log("error", error);
    });
  }

  // recommendData(){
  //   let that = this;
  //   let obj = "{\"type\":\"" + "recommend" + "\"}";
  //   this.http.get(UrlService.OTHER_CONFIG, {"callback": "JSONP_CALLBACK", "data": ToolService.aesEncode(obj)}).subscribe(res => {
  //     let data = res.json();
  //     if (data.code == ConfigService.SUCCESS_CODE) {
  //       let temp = data.data;
  //       let res=ToolService.aesDecodeToJson(temp);
  //       if(!ToolService.isEmpty(res)){
  //         that.recommend=res[0];
  //         console.log(res[0]);
  //       }
  //     } else if (data.code == ConfigService.FAIL_CODE) {
  //       this.popWin.toast(data.message);
  //     } else if (data.code == ConfigService.LOGIN_CODE) {
  //       this.navCtrl.navigateForward("/login");
  //     }
  //   }, error => {
  //     console.log("error", error);
  //   });
  // }

  copyFun(text:any){
      if(this.platform.is("cordova")){
        this.clipboard.copy(text).then(()=>{
          this.popWin.toast("链接已复制");
        });
      }else{
        let save = function (e) {
          e.clipboardData.setData('text/plain', text);   //保存到剪切板
          e.preventDefault(); //阻止默认行为
        }
        document.addEventListener('copy', save);
        document.execCommand("copy");     //使文档处于可编辑状态，否则无效
        this.popWin.toast("链接已复制");
      }
  }

  copyText(text:any){
      this.copyFun(text);
  }
  /**
   * 分享链接
   */
  share(){
    if(this.platform.is("cordova")){
      this.socialSharing.share("万漉国际","","",this.recommend.shareUrl).then(()=>{
        this.popWin.toast("分享成功");
      },()=>{
        this.popWin.toast("分享失败");
      }).catch(()=>{
          //alert("异常");
      });
    }else{
      this.popWin.toast("浏览器暂不能分享");
    }
  }
  /**
   * 保存图片
   */
  saveEwm(){
    let that=this;
    if(!this.platform.is("cordova")){
      this.popWin.toast("浏览器暂不能保存");
      return;
    }
    if(this.platform.is("cordova") && this.platform.is("android")){
      this.photoLibrary.requestAuthorization({
        "read": true,
        "write": true
      }).then(() => {
        that.photoLibrary.saveImage(that.recommend.img,'wanluhui').then(()=>{
          that.popWin.toast("保存图片成功");
        })
      }) .catch(err =>that.popWin.toast("没有权限访问图库"));
    }
    if(this.platform.is("cordova") && this.platform.is("ios")){
      const fileTransfer: FileTransferObject = this.transfer.create();
      const url = that.recommend.img;
      if(!ToolService.isAssetTypeAnImage(url)){
          that.popWin.toast("图片格式非法");
          return;
      }
      fileTransfer.download(url, this.file.documentsDirectory + 'wanluhui.png').then((entry) => {
      // console.log('download complete: ' + entry.toURL());
        that.popWin.toast("保存图片成功");
      }, (error) => {
        that.popWin.toast("保存图片失败");
      });
    }
    
  }

 
}
